﻿using ImTools;
using Prism.Ioc;
using SECSGEMServices;
using System;
using System.Collections.Generic;
using System.ComponentModel.Design;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using ZDevice.Event;
using ZZMES.Data;
using ZZMES.TCP;

namespace ZZMES.Process
{
    public class TcpStateEventArgs : DataEventArgs 
    {
        public int id;
        public int state;
    }
    public class TcpStateEvent : EventBase<TcpStateEventArgs> { }
    public  class ProcessInit:ProcessBase
    {

        
        private CancellationTokenSource cancellationTokenSource;
        public ProcessInit(IEventAggregator eventAggregator, IContainerProvider containerProvider, TCPHostService tcpHostService,DataProviderService dataProviderService)
            : base(eventAggregator, containerProvider, tcpHostService,dataProviderService)
        {
            eventAggregator.GetEvent<TcpEvent>().Subscribe(OnReceiveMsg);
            States = new Dictionary<string, int>();
            foreach (var device in DeviceNames) 
            {
                States.Add(device, 0);
            }
        }
        private Dictionary<string, int> PreStates;
        private Dictionary<string, int> States;
        private void OnReceiveMsg(TcpEventArgs args)
        {
            if (args.msg.Contains("S0F1")) 
            {
                string[] config = args.client.Split(':');
                var device = dataProviderService.communicateConfigs.FirstOrDefault(x => x.IP == config[0]);
                if (device != null)
                {
                    lock (States) 
                    {
                        States[device.Name] = 1;
                    }
                }
            }
        }

        public void Init() 
        {
            //加载SECS配置
            for(int i = 0; i < 10; i++) 
            {
                var service = serviceContainer.Resolve<KingSecsGemService>(DeviceNames[i]);
                service.Start(AppDomain.CurrentDomain.BaseDirectory+ "SECSConfig\\" + DeviceNames[i]+"\\"+ DeviceNames[i]+".kgprj");
                service.id = i;
            }
            cancellationTokenSource = new CancellationTokenSource();
            Task.Factory.StartNew(()=>StateWatcher(cancellationTokenSource.Token),cancellationTokenSource.Token);
        }

        //检测设备是否连接
        private void StateWatcher(CancellationToken cancellationToken) 
        {
            while (!cancellationToken.IsCancellationRequested) 
            {
                foreach(var s in States) 
                {
                    if (s.Value != -1) 
                    {
                        //通知客户端状态改变
                        TcpStateEventArgs args = new TcpStateEventArgs();
                        args.id = DeviceNames.IndexOf(s.Key);
                        args.state = s.Value; 
                        eventAggregator.GetEvent<TcpStateEvent>().PublishAsync(args);
                        lock (States) 
                        {
                            //值减1 如果是1就归0，如果是0，就归-1，以后不在检查
                            States[s.Key]--;
                        }
                    }
                }
                Thread.Sleep(TimeSpan.FromSeconds(10));
            }
        }
    }
}
